import { Commit } from 'vuex';
import { MenuState } from './type';
import storage from '@/utils/storage';
import { getMenuApi } from '@/api/app';
import { IsNotEmpty } from '@/utils/utils';
import { ElMessage } from 'element-plus';
import router from '@/router';

function collectMenuInfo(menus: Array<MenuState>, hashMap: any = {}, powerCode: any = []) {
    const result = {
        hashMap,
        powerCode
    };
    if (menus?.length) {
        menus.forEach(menu => {
            result.hashMap[menu.id] = menu.pid;
            if ([2, 3].includes(menu.type)) powerCode.push(menu.code);
            if (menu.children) collectMenuInfo(menu.children, result.hashMap, result.powerCode);
        });
    }

    return result;
}

const state = {
    menus: <Array<MenuState>>[],
    buttonCode: <Array<string>>[],
    menusRelationHash: {}
};

const mutations = {
    SET_MENUS(state: any, data: any): void {
        state.menus = data.menus;
        state.menusRelationHash = data.menusRelationHash;
    },
    SET_BUTTON_CODE(state: any, codeList: Array<string>): void {
        state.buttonCode = codeList;
    },
    clearMenu: (state: any): void => {
        state.menus = [];
        state.buttonCode = [];
        state.menusRelationHash = null;
    }
};

const actions = {
    // 获取菜单
    getMenu(context: { commit: Commit; state: any }) {
        return new Promise((resolve, reject) => {
            getMenuApi({})
                .then((res: any) => {
                    if (IsNotEmpty(res)) {
                        storage.remove('power-code');
                        const { hashMap, powerCode } = collectMenuInfo(res);
                        const menuData = {
                            menus: [...res],
                            menusRelationHash: hashMap
                        };
                        storage.set('power-code', powerCode);
                        context.commit('SET_MENUS', menuData);
                        resolve(menuData);
                    } else {
                        ElMessage.warning('当前暂无功能权限，请先联系管理员开通权限');
                        reject(new Error('获取菜单异常'));
                    }
                })
                .catch((err: Error) => {
                    reject(err);
                });
        });
    }
};

const Menu = {
    namespaced: true,
    state,
    mutations,
    actions
};

export default Menu;
